#' @title 多因子误差线聚合图 #errorline #3-factors #aggregate
#' @description 基于长数据格式创建多维度误差线图，支持1-3个因子变量。通过颜色编码和分面(facet)实现多维度数据对比，可视化均值、置信区间及个体趋势。
#' @examples
#' \dontrun{
#' # 单因子基础版：condition作为x轴主因子
#' aggr_errorline(df, x = "condition", dv = "rt")
#'
#' # 双因子增强版：添加stimulus颜色分组
#' aggr_errorline(df, x = "condition", hue = "stimulus", dv = "rt")
#'
#' # 三因子完整版：stimulus分面矩阵 + 颜色分组
#' aggr_errorline(df, x = "condition", hue = "stimulus",
#' dv = "rt", facets = c("stimulus"))
#' }

load("simulated_data.rdata")
library(dplyr)
library(ggplot2)
library(see)
library(stringr)

format_label <- function(label) {
  formatted_label <- str_replace_all(label, "_", " ")
  formatted_label <- str_to_title(formatted_label)
  return(formatted_label)
}

aggr_errorline <- function(df, x, dv, hue=x, ylabs = dv, facets = c(), leg_pos = "right", subject_id="subject_id") {
  
  if(is.grouped_df(df)){
    aa = df
  }else{
    aa = df %>% 
      group_by( across( all_of(unique(c(x,hue,facets,subject_id))) )) %>% 
      summarise(!!sym(dv) := mean(!!sym(dv)), .groups = "drop")
  }
  
  if(is.vector(x)){
    n_vars = length(x)
    if(n_vars>1){
      hue = x[2]
      x = x[1]
    }
    if(n_vars>2){
      facets = x[-1:2]
    }
  }
  
  line_group <- if (hue == x) 1 else sym(hue)
  
  pd1 <- position_dodge(0.15)
  a1 <- ggplot(
      aa, 
      aes(
        x = !!sym(x), 
        y = !!sym(dv),
        color = !!sym(hue)
      )
    ) +
    # Points (shape=17, size=2 like ggline)
    geom_point(
      stat = "summary",
      fun = "mean",
      shape = 17,
      size = 2
    ) +
    geom_line(
      aes(group = !!sym(subject_id)),
      linetype = "dotdash", 
      position = pd1,
      size = 0.8, colour = "#000000", alpha = 0.06
    ) + 
    geom_point(
      aes(group = !!sym(subject_id)),
      position = pd1,
      colour = "#000000", size = 3, shape = 20, alpha = 0.1
    ) +
    # Confidence intervals (ggline's add="mean_ci")
    geom_errorbar(
      stat = "summary",
      fun.data = mean_cl_normal,  # Mean ± 95% CI
      width = 0.2,
      linewidth = 1
    ) +
    # Individual lines (like ggline's plot_type="l")
    geom_line(
      stat = "summary", 
      fun = "mean",
      linewidth = 2,
      aes(group = !!line_group)
    ) +
    # Numeric x-axis (if x is numeric)
    if (is.numeric(aa[[x]])) {
      scale_x_continuous(breaks = unique(aa[[x]]))
    }
  
  
  if (length(facets) == 1) {
    facet.formula <- paste0("~", glue::backtick(facets)) %>% 
      stats::as.formula()
    a1 <- a1 + facet_wrap(facet.formula, labeller = labeller(.default = format_label))
  } else if (length(facets) == 2) {
    facet.formula <- paste(glue::backtick(facets), collapse = " ~ ") %>% 
      stats::as.formula()
    a1 <- a1 + facet_grid(facet.formula, labeller = labeller(.default = format_label))
  }
  a1
  a1 = a1 +
    labs(x="", color="", fill="", shape="")+
    theme_modern() +
    theme(
      strip.text.x = element_text(size = 14),
      legend.position = leg_pos,
      legend.key.width= unit(0.5, 'cm'),
      legend.spacing = unit(0.1, 'cm'),
      legend.margin = margin(t = 0, r = 0, b = 5, l = 5),
      legend.box.spacing = unit(0.1, "cm")
    )
  a1
}


# aggr_errorline(
#   df,
#   x = "condition",
#   dv = "rt"
# )
# aggr_errorline(
#   df,
#   x = "condition",
#   hue = "stimulus",
#   dv = "rt"
# )
aggr_errorline(
  df,
  x = "condition",
  hue = "stimulus",
  dv = "rt",
  facets = c("stimulus")
)
